from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
import json

from .models import Book

# 增加书籍
@require_http_methods(["GET"])
def add_book(request):
    response = {}
    try:
        book = Book(book_name=request.GET.get('book_name'))
        book.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
# def add_book(request):
#     book_name = request.GET.get('book_name', '')
#     if book_name:
#         # 添加书籍的逻辑（例如保存到数据库）
#         return JsonResponse({'error_num': 0, 'msg': '书籍添加成功'})
#     else:
#         return JsonResponse({'error_num': 1, 'msg': '书名不能为空'})



# # 展示所有书籍
@require_http_methods(["GET"])
def show_books(request):
    response = {}
    try:
        books = Book.objects.filter()
        response['list'] = json.loads(serializers.serialize("json", books))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
# def show_books(request):
#     # 显示书籍列表的逻辑
#     return JsonResponse({'books': []})